#include "SensorInfo.h"
#include "Fpga.h"
#include "Mcu.h"
#include "MiscData.h"
SensorInfo::SensorInfo(QObject *parent) : QObject(parent) {
    m_waitCount = 0;
    connect(&m_querySensorTimer, &QTimer::timeout, this, &SensorInfo::onQuerySensor);
    connect(Mcu::getInstance(), &Mcu::reportMcuCurrSensorType, this, &SensorInfo::onHaveSensorSwitch);
    connect(&m_waitResponseTimer, &QTimer::timeout, [&](){
        if(RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateMcu>=0) {///<升级MCU时直接结束
            m_waitResponseTimer.stop();
            m_querySensorTimer.stop();
            return;
        }
        Mcu::getInstance()->reportSensorState(m_fpgaSensorState);
        m_waitCount++;
        if(m_waitCount>=10) {
            m_waitCount = 0;
            m_waitResponseTimer.stop();
        }
    });

    connect(&m_queryImageErrorTimer, &QTimer::timeout, this,[]() {
        if(RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateMcu>=0) {
            return ;
        }

        uint32_t value;///< 1-颜色异常
        value = Fpga::getInstance()->readRegister(0X40230);
        if(!value)Mcu::getInstance()->reportSensorImageError();///< 颜色异常
    });
   m_querySensorTimer.start(200);
   m_queryImageErrorTimer.start(30);
}

void SensorInfo::onQuerySensor() {
    uint32_t value;///< 1-插入 0-拔出
    value = Fpga::getInstance()->readRegister(0x14);
    if(m_fpgaSensorState != value) {
    m_fpgaSensorState = value;
    if(RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateMcu>=0) {///<升级MCU时直接结束
        m_querySensorTimer.stop();
        return;
    }
    Mcu::getInstance()->reportSensorState(m_fpgaSensorState);
    if(!m_fpgaSensorState)  {
        qDebug()<<"镜子插入";
    } else {
        qDebug()<<"镜子拔出";
    }
     m_waitResponseTimer.start(200);
    }
}

void SensorInfo::onHaveSensorSwitch(uint8_t value) {
    m_waitResponseTimer.stop();
    m_waitCount = 0;

    if(m_sensorType!=value){
        m_sensorType = value;
        emit sensorTypeChanged();
    }
}

bool SensorInfo::getIsOpenRegisterOperationPage() const
{
    return m_isOpenRegisterOperationPage;
}

void SensorInfo::setIsOpenRegisterOperationPage(bool value)
{
    m_isOpenRegisterOperationPage = value;
}

uint8_t SensorInfo::getSensorType() const {
    return m_sensorType;
}


